package com.grayson.wordsfilter.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.dfa.WordTree;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;

/**
 * BeanConfig
 *
 * @Description:
 * @Author: grayson
 * @Version 1.0
 * @Date: 2023-05-11 23:16
 **/
@Configuration
public class BeanConfig {

    @Bean
    public WordTree initWordTree() throws IOException {
        WordTree wordTree = new WordTree();
        Set<String> wordSet = getSensitiveWords();
        wordTree.addWords(wordSet);
        return wordTree;
    }

    private Set<String> getSensitiveWords() throws IOException {
        File dirFile = ResourceUtils.getFile("classpath:wordfiles");

        List<File> fileList = FileUtil.loopFiles(dirFile);
        if(CollectionUtil.isEmpty(fileList)){
           return null;
        }
        Set<String> wordSet = new HashSet<>();
        for (File file : fileList) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;

            while ((line = reader.readLine()) != null) {
                String[] words = line.split("，|,|、");
                for(int i = 0; i < words.length;i++){
                    String word = words[i].trim();
                    if(word.length() > 0){
                        wordSet.add(word);
                    }
                }
            }
        }
        return wordSet;
    }
}